package com.thrd.basicframework.ui.webview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.thrd.basicframework.R;
import com.thrd.basicframework.utils.HtmlUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


/**
 * @author: ${唐杰}
 * @date: 2021/3/26
 */
public class JieWebView extends WebView {
    private int pading=0;
    public JieWebView(@NonNull Context context) {
        this(context,null,0);
    }

    public JieWebView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public JieWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }


    @SuppressLint("SetJavaScriptEnabled")
    private  void initView(){
        pading = getContext().getResources().getDimensionPixelSize(R.dimen.qb_px_9);

//        WebSettings webSetting=this.getSettings();
//        //是否支持缩放，默认true
//        webSetting.setSupportZoom(true);
//
//// 是否使用WebView内置的缩放组件，由浮动在窗口上的缩放控制和手势缩放控制组成，默认false
//        webSetting.setBuiltInZoomControls(false);
//
//// 是否显示窗口悬浮的缩放控制，默认true
//        webSetting.setDisplayZoomControls(false);
//
//// 是否启动概述模式浏览界面，当页面宽度超过WebView显示宽度时，缩小页面适应WebView。默认false
//        webSetting.setLoadWithOverviewMode(false);
//
//        webSetting.setJavaScriptEnabled(true);
//
//        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);

        WebSettings webSettings = this.getSettings();
        webSettings.setLoadWithOverviewMode(true);
        //  webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);

        //支持javascript
        webSettings.setJavaScriptEnabled(true);
        //是否可以缩放
        webSettings.setSupportZoom(false);
        // 设置出现缩放工具
        webSettings.setBuiltInZoomControls(false);
        //扩大比例的缩放
        webSettings.setUseWideViewPort(false);
        //自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setLoadWithOverviewMode(true);
        //增加WebView对localStorage的支持
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccess(true);
        //不使用缓存 LOAD_NO_CACHE   优先加载缓存LOAD_CACHE_ELSE_NETWORK
        //settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //解决图片不显示
        webSettings.setBlockNetworkImage(false);
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);



        //   webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
//先阻塞加载图片
        //   webSettings.setBlockNetworkImage(false);
//为了演示，不缓存
        // webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
// 添加js交互接口类，并起别名 imagelistner
        addJavascriptInterface(new JSTest(getContext()), "JSTest");
        // mWebView.setWebViewClient(new MyWebViewClient());

        setWebViewClient(new CustomWebViewClient());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //感觉手机重新计算高度
        int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, mExpandSpec);
    }


    public void loadDataWithBaseURL(String content){
        content=   getHtmlData(content);
        content= HtmlUtils.getNewContent(content);
        loadDataWithBaseURL(null, getNewData(content), "text/html", "utf-8", null);
        // loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
    }

    /**
     * 设置img标签下的width为手机屏幕宽度，height自适应
     *
     * @param data html字符串
     * @return 更新宽高属性后的html字符串
     */
    private String getNewData(String data) {
        Document document = Jsoup.parse(data);

        Elements pElements = document.select("p:has(img)");
        for (Element pElement : pElements) {
            //    pElement.attr("style", "text-align:center");
            pElement.attr("max-width", String.valueOf(this.getWidth() + "px"))
                    .attr("height", "auto");
        }
        Elements imgElements = document.select("img");
        for (Element imgElement : imgElements) {
            //重新设置宽高
            imgElement.attr("max-width", "100%")
                    .attr("height", "auto");
            imgElement.attr("style", "max-width:100%;height:auto");
            // imgElement.attr("onerror","file:///android_asset/loading_image_default.png");
        }
        Log.i("newData:", document.toString());
        return document.toString();
    }

    /**
     * 富文本适配
     */
    private String getHtmlData(String bodyHTML) {
        String head = "<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:auto; height:auto;}</style>"
                + "</head>";
        return "<html>" + head + "<body style=\"padding: 0 "+ pading+"px\">" + bodyHTML + "</body></html>";
    }

}
